import {
	HOST
} from '@/config'
import {
	getCurrentPath
} from '@/utils/tools'
import store from '@/store'

function startLoading() {
	uni.showLoading({
		title: '请稍候...',
		// #ifdef MP-WEIXIN 
		mask: true,
		// #endif
	});
}

function endLoading() {
	uni.hideLoading();
}

let needLoadingRequestCount = 0;
let pageJumpLock;

function showFullScreenLoading(hasLoading = true) {
	if (needLoadingRequestCount === 0) {
		pageJumpLock = true;
		if (hasLoading) {
			uni.showNavigationBarLoading();
			startLoading();
		}
	}
	needLoadingRequestCount++;
};

function tryHideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		uni.hideNavigationBarLoading();
		uni.stopPullDownRefresh();
		endLoading();
	}
};

function adornUrl(url = '') {
	return url.startsWith('http') ? url : HOST + (url || '')
}

export default (param) => {
	let httpDefaultOpts = {
		url: adornUrl(param.url),
		data: Object.assign(param.data || {}, (param.identity && store.state[param.identity].token) ? {
			token: store.state[param.identity].token
		} : {}),
		method: param.method || 'POST',

		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
	};

	showFullScreenLoading(param.hasLoading);

	return new Promise((resolve, reject) => {
		uni.request(httpDefaultOpts).then(data => {
			tryHideFullScreenLoading();
			let [error, res] = data;
			if (res.data.code == 401 || res.data.msg === '您的登录凭证已失效，请重新登录') { //登录失效
				if (pageJumpLock) {
					pageJumpLock = false;
					if (param.identity === 'user' && getCurrentPath() !== 'pages/user/index/index') {
						store.commit('login', '')
						uni.showModal({
							title: '提示',
							content: '登录已失效!',
							showCancel: false
						}).then(res => {
							if (getCurrentPath() != 'pages/main/mine') {

								uni.reLaunch({
									url: '/pages/main/mine'
								})
							}
						})
					} else if (param.identity === 'admin') {
						uni.reLaunch({
							url: `/pages/admin/login`
						});
					} else {
						resolve(typeof(res.data.code != "undefined") ? res.data : res);
					}
				}
			} else if (res.data.code == 200 || param.default) {
				resolve(res.data);
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.msg || '操作失败'
				});
				reject(data);
			}
		}).catch(
			(response) => {
				reject(response);
				tryHideFullScreenLoading();
			}
		);
	});
};
